package cdp.tarasenko.epamevospring.service;

import cdp.tarasenko.epamevospring.model.CityGeoLocation;
import com.google.code.geocoder.Geocoder;
import com.google.code.geocoder.GeocoderRequestBuilder;
import com.google.code.geocoder.model.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Oleksandr_Tarasenko
 */
@Service
public class GeoLocationService {

    public CityGeoLocation getLocationFromGoogleGeocode(String city) {
        CityGeoLocation geoData = new CityGeoLocation();
        final Geocoder geocoder = new Geocoder();
        GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(city).setLanguage("en").getGeocoderRequest();
        GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
        GeocoderStatus status = geocoderResponse.getStatus();
        switch (status){
            case OVER_QUERY_LIMIT:
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                geoData = getLocationFromGoogleGeocode(city);
                break;
            case OK:
                GeocoderResult result = geocoderResponse.getResults().get(0);
                LatLng latLng = result.getGeometry().getLocation();
                geoData.setPos(new CityGeoLocation.Position(latLng.getLat().doubleValue(), latLng.getLng().doubleValue()));
                geoData.setCity(city);
                geoData.setCountry(getCountryFromGeocoderResult(result));
                break;
            default:
                System.out.println("Can't get location of city " + city + ". Error: " + status);
        }

        return geoData;
    }

    private String getCountryFromGeocoderResult(GeocoderResult res) {
        List<GeocoderAddressComponent> addrComponents = res.getAddressComponents();
        for (GeocoderAddressComponent comp : addrComponents) {
            if (comp.getTypes().get(0).equals("country")) {
                return comp.getLongName();
            }
        }
        System.out.println("Cant extract country!");
        return "";
    }
}
